import logging
from logging.handlers import RotatingFileHandler
import os

# 日志目录
LOG_DIR = "../logs"
os.makedirs(LOG_DIR, exist_ok=True)

LOG_FILE = os.path.join(LOG_DIR, "app.log")

logger = logging.getLogger("tcp_logger")
logger.setLevel(logging.DEBUG)

# ANSI 颜色
COLORS = {
    'DEBUG': '\033[36m',    # 青色
    'INFO': '\033[32m',     # 绿色
    'WARNING': '\033[33m',  # 黄色
    'ERROR': '\033[31m',    # 红色
    'CRITICAL': '\033[41m', # 红底
}
RESET_COLOR = '\033[0m'

class ColorFormatter(logging.Formatter):
    def format(self, record):
        msg = super().format(record)
        color = COLORS.get(record.levelname, RESET_COLOR)
        return f"{color}{msg}{RESET_COLOR}"

# 控制台 handler
console_handler = logging.StreamHandler()
console_handler.setLevel(logging.DEBUG)
console_formatter = ColorFormatter('[%(asctime)s] [%(levelname)s] %(message)s',
                                   datefmt='%Y-%m-%d %H:%M:%S')
console_handler.setFormatter(console_formatter)

# 文件 handler
file_handler = RotatingFileHandler(LOG_FILE, maxBytes=5*1024*1024, backupCount=5, encoding='utf-8')
file_handler.setLevel(logging.INFO)
file_formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] %(message)s',
                                   datefmt='%Y-%m-%d %H:%M:%S')
file_handler.setFormatter(file_formatter)

logger.addHandler(console_handler)
logger.addHandler(file_handler)

# 封装函数
def debug(msg): logger.debug(msg)
def info(msg): logger.info(msg)
def warning(msg): logger.warning(msg)
def error(msg): logger.error(msg)
def critical(msg): logger.critical(msg)